package cn.edu.hbpu.service.impl;

import cn.edu.hbpu.common.R;
import cn.edu.hbpu.entity.Goods;
import cn.edu.hbpu.handler.CustomException;
import cn.edu.hbpu.mapper.GoodsMapper;
import cn.edu.hbpu.service.GoodsService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static cn.edu.hbpu.common.Constants.PAGING_MAX_RETURN_COUNT;

/**
 * @author lcy
 * @date 2022/8/23 14:07
 * @description
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public R<Page<Goods>> pagingQueryGoods(int page, int pageSize) {
        if (pageSize > PAGING_MAX_RETURN_COUNT) {
            pageSize = PAGING_MAX_RETURN_COUNT;
        }
        Page<Goods> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        // 指定查询的字段
        queryWrapper.select(Goods::getGId, Goods::getGName, Goods::getImage, Goods::getOriginalPrice, Goods::getDiscountPrice, Goods::getDescription, Goods::getClickRate, Goods::getCollectionRate);
        // 根据点击量和收藏量进行降序排序
        queryWrapper.orderByDesc(Goods::getClickRate).orderByDesc(Goods::getCollectionRate);
        // 查询上架的商品
        queryWrapper.eq(Goods::getStatus, 1);

        goodsMapper.selectPage(pageInfo, queryWrapper);
        return new R<>(HttpStatus.HTTP_OK, pageInfo);
    }

    @Override
    public R<Goods> getGoodsInfo(String gId) {
        if (StrUtil.isBlank(gId)) {
            throw new CustomException("gId不能为空");
        }
        Goods goods = goodsMapper.selectById(gId);
        return new R<>(HttpStatus.HTTP_OK, goods);
    }
}
